<template>
  <div>
    <transition name="dis_list">
      <div class="list_box" v-if="listIsDis">
        <div class="big_box">
          <div class="music">
            <div class="videoport">
              <div class="song-warp">
                <div
                  class="song-img"
                  :class="[
                    $store.state.isPlay ? 'active' : 'pause',
                    $store.state.isMusicLoad ? '' : 'active',
                  ]"
                >
                  <img src="@/components/player/images/disc.png" alt="" />
                  <img
                    id="img "
                    :src="audio.al.picUrl"
                    class="musicAvatar"
                    alt
                  />
                </div>
              </div>
            </div>
            <div class="songWords">
              <div class="music_dis">
                <!-- <div class="dis_list" @click="DisList">···</div> -->
                <p class="music_title">{{ audio.name }}</p>
                <p class="music_intro">歌手: {{ audio.ar[0].name }}</p>
                <lyrics-scroll :lyric="lyric"></lyrics-scroll>

                <!-- <ul class="music_words">
            <div class="music_words_box" :style="{ top: wordsTop + 'px' }">
              <li
                v-for="(item, index) in musicWords"
                :key="index"
                class="music_word"
                :class="{ word_highlight: wordIndex == index }"
              >
                {{ item }}
              </li>
            </div>
          </ul> -->
              </div>
            </div>
          </div>
          <div class="play">
            <div class="bar-panel">
              <div class="music-info">
                <div class="picimg music-panel">
                  <img :src="audio.al.picUrl" />
                </div>
                <div class="music-desc">
                  <p class="music-name">{{ audio.name }}</p>
                  <p class="auther">{{ audio.ar[0].name }}</p>
                </div>
              </div>
              <div class="music-set">
                <div class="picimg premusic" @click="changeMusic('pre')">
                  <img
                    src="@/components/player/images/playbar_btn_next.png"
                    alt
                  />
                </div>
                <div class="playmusic" @click="open()">
                  <img
                    v-if="this.$store.state.isPlay"
                    src="@/components/player/images/playbar_btn_pause.png"
                    alt
                  />
                  <img
                    v-else
                    src="@/components/player/images/playbar_btn_play.png"
                    alt
                  />
                </div>
                <div class="picimg" @click="changeMusic('next')">
                  <img
                    src="@/components/player/images/playbar_btn_next.png"
                    alt
                  />
                </div>
                <!-- 进度条 -->
                <div class="pro">
                  <span class="currentTime">{{ currentTime }}</span>
                  <!-- :value 是单向的  要实现双向要v-model -->
                  <el-slider
                    class="progressSlider"
                    v-model="timeProgress"
                    :show-tooltip="false"
                    @change="changeProgress"
                  ></el-slider>
                  <span class="totalTime">{{ duration }}</span>
                </div>
              </div>
              <div class="rg">
                <div class="volumeControl">
                  <i
                    class="iconfont2 icon2-yinliang"
                    @click="changeMutedState"
                  ></i>
                  <el-slider
                    class="volumeSlider"
                    v-model="volume"
                    @input="changeVolume"
                    :show-tooltip="false"
                  ></el-slider>
                </div>
                <div class="picimg" @click="playList">
                  <img
                    src="@/components/player/images/playbar_btn_playlist.png"
                    alt
                  />
                </div>
              </div>
            </div>
          </div>
          <!-- 抽屉 -->
          <el-drawer
            :visible.sync="drawer"
            :with-header="false"
            width="300"
            :modal="false"
          >
            <h3 class="drawerTitle">播放列表</h3>
            <div class="drawerHeader">总{{ musicList.length }}首</div>
            <el-table
              :data="musicList"
              stripe
              style="width: 100%"
              :show-header="false"
              @row-dblclick="clickRow"
              highlight-current-row
              lazy
            >
              <el-table-column prop="name" width="180px"> </el-table-column>
              <el-table-column prop="ar[0].name" width="80px">
              </el-table-column>
              <!-- <el-table-column prop="dt" width="70px"> </el-table-column> -->
            </el-table>
          </el-drawer>
        </div>
      </div>
    </transition>
    <div class="box" @click="DisList">
      <span
        ><i class="iconfont2 icon2-erji-toudaishierji-shengyin-yinle"></i
      ></span>
    </div>
    <audio
      :src="musicUrl"
      id="play"
      ref="audio"
      @timeupdate="updateTime"
      @ended="changeMusic('next')"
      @play="changeState(true)"
      @pause="changeState(false)"
      autoplay
      @canplay="eventMusic"
    ></audio>
  </div>
</template>
<script>
import LyricsScroll from "@/components/player/components/LyricsScroll.vue";
import {
  getWords,
  getMusicInfo,
  getMusicUrl,
  getHotMusic,
} from "@/components/player/api/music";

// 保存当前音量
let volumeSave = 0;
// import Music from "@/views/Music.vue";
export default {
  name: "",
  // components: { Music },
  components: { LyricsScroll },
  props: [""],
  watch: {
    "$store.state.musicId"(id) {
      console.log("vuex中的id发生了变化");
      // 先暂停当前播放的音乐
      this.pauseMusic();
      this.lyric = [[0, "正在加载歌词"]];
      // 更新当前歌曲信息
      this.getMusicInfo(id);

      this.getLyric(id);

      this.getMusicDetailFromMusicList();
      this.getMusicDetail(id);
    },
    // 监听currentIndex的变化
    "$store.state.currentIndex"(currentIndex, lastIndex) {
      if (this.hasDrawerOpend) {
        this.handleDrawerListDOM(currentIndex, lastIndex);
      }
    },
    // 监听播放状态
    "$store.state.isPlay"(isPlay) {
      if (isPlay) {
        this.$refs.audio.play();
      } else {
        this.$refs.audio.pause();
      }
    },
  },
  data() {
    return {
      listIsDis: false,
      timeProgress: 0,
      lyric: [[0, "正在加载歌词"]], // 歌词 中英文

      lyricIndex: "0", // 当前显示的歌词
      isMuted: false, // 是否静音 默认不静音
      volume: 30, // 音频音量
      musicInfo: {},
      likeList: [],
      id: 3778678,
      playType: "order",
      musicList: [],
      currentMusicIndex: 0,
      drawer: false,
      musicUrl: "",
      audio: {},
      duration: "00:00",
      currentTime: "00:00",
    };
  },
  created() {
    this._getInfo();
    this.getMusicList();
  },
  mounted() {},
  methods: {
    DisList() {
      console.log(this.listIsDis);
      this.listIsDis = this.listIsDis ? false : true;
    },
    // 请求歌曲的url
    async getMusicDetail(id) {
      this.$store.commit("updateMusicLoadState", true);
      let result = await getMusicUrl(id);
      // console.log(musicDetail);
      // console.log(result);
      // 获取不到url
      if (result.data.data[0].url == null) {
        this.$message.error("该歌曲暂无版权，将为您播放下一首歌曲");
        this.changeMusic("next");
        return;
      }
      this.musicUrl = result.data.data[0].url;
      this.$store.commit("updateMusicLoadState", false);
    },
    // 根据id找到 musicList中对应的musicDetail
    getMusicDetailFromMusicList() {
      let index = this.musicList.findIndex(
        (item) => item.id == this.$store.state.musicId
      );
      console.log(index);
      if (index != -1) {
        // 记录当前音乐的index
        this.currentMusicIndex = index;
        // 将索引传至vuex
        this.$store.commit("updateCurrentIndex", index);
        this.musicDetail = this.musicList[index];
        this.duration = this.musicList[index].dt;
      }
    },
    async getMusicList() {
      let result = await getHotMusic(this.id);
      this.musicList = result.data.playlist.tracks.splice(0, 200);
    },
    async getMusicInfo(id) {
      let result = await getMusicInfo(id);
      this.audio = result.data.songs[0];
    },
    _getInfo() {
      getMusicInfo(1997438791).then((res) => {
        this.audio = res.data.songs[0];
        console.log(this.audio);
      });
      this.getLyric(1997438791);

      getMusicUrl(1997438791).then((res) => {
        if (
          res.data.data[0].url == null ||
          res.data.data[0].url == "" ||
          res.data.data[0].url == undefined
        ) {
          console.log("空");
        } else {
          this.musicUrl = res.data.data[0].url.replace("http://", "https://");
        }
      });
    },

    eventMusic() {
      console.log("准备播放");
      // this.duration = this.$refs.audio.duration;
      this.duration = this.conversion(this.$refs.audio.duration);
    },
    changeState(state) {
      this.$store.commit("changePlayState", state);
    },
    updateTime(e) {
      let time = this.$refs.audio.currentTime;
      // 将当前播放时间保存到vuex
      this.$store.commit("updateCurrentTime", time);
      let duration = this.$refs.audio.duration.toFixed(3);
      let currentTime = this.$refs.audio.currentTime;
      this.duration = this.conversion(duration); //歌曲长度
      this.currentTime = this.conversion(currentTime); //播放位置
      this.timeProgress = (currentTime / duration) * 100;
    },
    // 拖动进度条的回调
    changeProgress(e) {
      // console.log(e);
      // 修改当前播放时间
      this.currentTime = Math.floor((e / 100) * durationNum);
      // 改变audio的实际当前播放时间
      this.$refs.audio.currentTime = this.currentTime;
    },

    conversion(value) {
      // 播放展示时间处理
      //处理时间
      let minute = Math.floor(value / 60); //将时间取整数
      minute = minute.toString().length === 1 ? "0" + minute : minute; //判断时间长度是否为1 不为1则自动添加 0
      let second = Math.round(value % 60);
      second = second.toString().length === 1 ? "0" + second : second;
      return `${minute}:${second}`;
    },

    open() {
      !this.$store.state.isPlay ? this.playMusic() : this.pauseMusic();
    },
    // 播放音乐的函数
    playMusic() {
      this.$refs.audio.play();
    },
    // 暂停音乐的函数
    pauseMusic() {
      this.$refs.audio.pause();
    },
    async getLyric(id) {
      let res = await getWords(id);
      //   console.log(res);
      let lyrics = res.data.lrc.lyric;
      // 对获取到的歌词进行处理
      let arr = lyrics.split("\n");
      let array = [];
      // let obj = {};
      let time = "";
      let value = "";
      let result = [];

      //去除空行
      arr.forEach((item) => {
        if (item != "") {
          array.push(item);
        }
      });
      arr = array;
      arr.forEach((item) => {
        time = item.split("]")[0];
        value = item.split("]")[1];
        //去掉时间里的中括号得到xx:xx.xx
        var t = time.slice(1).split(":");
        //将结果压入最终数组
        result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]), value]);
      });

      this.lyric = result;
      // console.log(this.lyric);
    },
    ended() {},
    nextMusic() {},
    playList() {
      this.drawer = !this.drawer;
    },
    // 音量控制
    // 拖动音量条的回调
    changeVolume(e) {
      // 改变audio的音量
      // input事件 实时触发
      this.$refs.audio.volume = e / 100;
      if (this.isMuted && e > 0) {
        this.isMuted = false;
      } else if (e == 0 && this.isMuted == false) {
        this.isMuted = true;
      }
    },
    changeMutedState() {
      if (this.isMuted) {
        this.volume = volumeSave;
      } else {
        volumeSave = this.volume;
        this.volume = 0;
      }
      console.log(volumeSave, this.isMuted);
      this.isMuted = !this.isMuted;
    },
    // 切歌函数
    changeMusic(type, id) {
      if (type == "click") {
        // 点击抽屉row进行切歌
        this.$store.commit("updateMusicId", id);
      } else if (type == "pre") {
        let currentMusicIndex = this.currentMusicIndex;
        let preIndex;
        if (this.playType == "order") {
          preIndex =
            currentMusicIndex - 1 < 0
              ? this.musicList.length - 1
              : currentMusicIndex - 1;
        } else if (this.playType == "random") {
          if (this.musicList.length == 1) {
            preIndex = currentMusicIndex;
          } else {
            // Math.floor(Math.random()*10); 可均衡获取0到9的随机整数。
            preIndex = currentMusicIndex;
            while (preIndex == currentMusicIndex) {
              preIndex = Math.floor(Math.random() * this.musicList.length);
            }
          }
        }
        console.log(this.musicList[preIndex].id);
        this.$store.commit("updateMusicId", this.musicList[preIndex].id);
      } else if (type == "next") {
        let currentMusicIndex = this.currentMusicIndex;
        let nextIndex;
        if (this.playType == "order") {
          nextIndex =
            currentMusicIndex + 1 == this.musicList.length
              ? 0
              : currentMusicIndex + 1;
        } else if (this.playType == "random") {
          if (this.musicList.length == 1) {
            nextIndex = currentMusicIndex;
          } else {
            // Math.floor(Math.random()*10); 可均衡获取0到9的随机整数。
            nextIndex = currentMusicIndex;
            while (nextIndex == currentMusicIndex) {
              nextIndex = Math.floor(Math.random() * this.musicList.length);
            }
          }
        }
        // console.log(this.musicList[nextIndex].id);
        this.$store.commit("updateMusicId", this.musicList[nextIndex].id);
      }
    },
    clickRow(row) {
      console.log(row.id);
      this.changeMusic("click", row.id);
    },
  },
};
</script>
<style lang='less' scoped>
* {
  padding: 0px;
  margin: 0px;
  text-decoration: none;
  font-family: Consolas, "微软雅黑";
  box-sizing: border-box;
}
.list_box {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-image: linear-gradient(
    135deg,
    #ffdee9 0%,
    #b5fffc 50%,
    #ffffff 100%
  );
  z-index: 499;
  transition: all 0.5s;
}
// .dis_list-enter,
// .dis_list-leave-to {
//   opacity: 0;
// }
.box {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  // background-color: #fff;
  position: fixed;
  z-index: 500;
  bottom: 30px;
  left: 30px;
  transition: all 0.5s;
  color: rgb(239, 15, 30);
  text-align: center;
}
.box .iconfont2 {
  font-size: 40px;
  cursor: pointer;
}
.big_box {
  margin-top: 60px;
  height: calc(100vh - 60px);
  // background-color: #fff;
  position: relative;
}
.play {
  width: 100%;
  height: 80px;
  background-color: #ffffff;
  position: absolute;
  bottom: 0;
}
.music {
  display: flex;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 60px);
}
.videoport {
  // background: rgb(59, 198, 24);
  height: 100%;
  // width: 40%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  margin-right: 150px;
}

.song-warp {
  /* animation: active 10s linear .3s infinite; */
  margin: 0 auto;
  position: relative;
}

.song-img {
  width: 220px;
  height: 220px;
  position: relative;
  top: -12px;
}

.song-img img:nth-child(1) {
  width: 100%;
}
.song-img .musicAvatar {
  position: absolute;
  top: 35px;
  left: 35px;
  width: 150px;
  z-index: -1;
}

@keyframes active {
  0% {
    transform: rotate(0);
  }

  100% {
    transform: rotate(360deg);
  }
}

.active {
  animation: active 20s linear infinite;
}

.pause {
  animation-play-state: paused;
  -webkit-animation-play-state: paused;
}
.songWords {
  // background: rgb(145, 151, 231);
  height: 100%;
  width: 26%;
}
.music_dis {
  margin-top: 25px;
}
.music_title {
  width: 100%;
  height: 40px;
  text-align: center;
  color: #eddada;
  line-height: 60px;
  font-size: 26px;
}
.music_intro {
  width: 100%;
  height: 40px;
  text-align: center;
  color: #d5c8c8;
  line-height: 40px;
  font-size: 14px;
}
.music_words_box {
  width: 100%;
  height: auto;
  position: absolute;
  top: 0px;
  transition: all 0.5s;
}
.music_words {
  width: 240px;
  height: 400px;
  margin: auto;
  color: rgba(255, 255, 255, 0.6);
  text-align: center;
  overflow: hidden;
  position: relative;
}
.music_words li {
  list-style: none;
  font-size: 12px;
  margin-top: 5px;
  min-height: 18px;
}
.bar-panel {
  padding: 5px;
  display: flex;
  justify-content: space-between;
}

.music-info,
.music-set {
  align-items: center;
  display: flex;
  justify-content: flex-start;
}

.picimg {
  width: 60px;
  height: 60px;
}
.premusic {
  transform: rotate(180deg);
}
.playmusic {
  width: 35px;
  height: 40px;
}

.music-panel img {
  border-radius: 5px;
}

.picimg img,
.play img {
  background-image: cover;
  width: 100%;
  height: 100%;
}

.music-desc {
  padding-left: 10px;
}

.music-desc .music-name {
  color: #666;
  font-size: 14px;
}

.music-desc .auther {
  color: #999999;
  font-size: 10px;
}

/* 进度条 */
.pro {
  display: flex;
  align-items: center;
}
.pro .progresss {
  background-color: #ea0808;
  height: 2px;
  width: 75%;
}
/deep/ .el-slider__bar {
  background-color: #ff4e4e !important;
}
/deep/ .el-slider__button {
  border: 1px solid #ccc !important;
  width: 10px !important;
  height: 10px !important;
}
/deep/.el-slider__runway {
  height: 5px !important;
}
/deep/ .el-slider__bar {
  height: 5px !important;
}
.currentTime,
.totalTime {
  font-size: 12px;
  transform: scale(0.85);
  color: rgb(244, 11, 11);
  margin: 0 5px;
  width: 30px;
  text-align: center;
}
.progressSlider {
  width: 300px;
}
// .pro span {
//   font-size: 12px;
//   color: #e60909;
// }
.music-panel {
  transform: rotate(360deg);
}
.rg {
  display: flex;
  align-items: center;
  position: relative;
}

.volumeControl {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.icon-yinliang {
  font-size: 18px;
  margin-right: 7px;
}

.volumeSlider {
  width: 55px;
}
.drawerHeader {
  font-size: 12px;
  transform: scale(0.9);
  color: #aaa;
  padding: 15px 0;
}
.drawerTitle {
  margin: 15px;
}
/deep/ .el-drawer__container {
  // margin-top: 60px;
  height: calc(100vh - 80px) !important;
}
/deep/ .rtl {
  width: 270px !important;
}
@media only screen and (max-width: 992px) {
  .box {
    position: fixed;
    bottom: 75px;
    left: 0;
    height: auto;
  }
  .play {
    .music-desc {
      display: none;
    }
  }
  .volumeControl {
    display: none;
  }
  .pro {
    position: absolute;
    bottom: 0;
    width: 156px;
  }
  /deep/ .el-slider__button-wrapper .el-tooltip,
  .el-slider__button-wrapper::after {
    margin-top: 12px;
  }
  .videoport {
    display: none;
  }
  .songWords {
    width: 100%;
  }
}
</style>